package cn.edu.ctbu.datajpa01.service.impl;

import cn.edu.ctbu.datajpa01.domain.Student;
import cn.edu.ctbu.datajpa01.domain.Teacher;
import cn.edu.ctbu.datajpa01.exception.REnum;
import cn.edu.ctbu.datajpa01.exception.RException;
import cn.edu.ctbu.datajpa01.repository.StudentRepository;
import cn.edu.ctbu.datajpa01.repository.TeacherRepository;
import cn.edu.ctbu.datajpa01.service.TeacherService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import java.util.List;



@Service
public class TeacherServiceImpl implements TeacherService {


    @Autowired
    TeacherRepository teacherRepository;

    public List<Teacher> findAll(){
        return teacherRepository.findAll();
    }



    /**
     * 只分页的查询
     * @param pageable
     * @return
     */

    public Page<Teacher> findAll(Pageable pageable) {
        return teacherRepository.findAll(pageable);
    }
    /**
     * 带过滤
     * @param studentExample
     * @param pageable
     * @return
     */
    public Page<Teacher> findAll(Example<Teacher> studentExample, Pageable pageable){
        return teacherRepository.findAll(studentExample,pageable);
    }

    /**
     * 按id进行查询
     * @param id 主键，整数
     * @return
     */
    public Teacher findById(Integer id){
        return teacherRepository.findById(id).orElse(null);
    }

    /**
     * 按名字查询，like
     * @param name
     * @return
     */

    public List<Teacher> findByName(String name){
        return teacherRepository.findByNameLike(name);
    }

//    /**
//     * 按名字和密码查询
//     * @param name
//     * @param password
//     * @return
//     */
//    public List<Teacher> findByNameAndPassword(String name,String password){
//        return teacherRepository.findByNameAndPassword(name,password);
//    }

    public Teacher findByNameAndPassword(String name ,String password) throws Exception{
        Teacher teacher=teacherRepository.findByNameAndPassword(name,password);
        if(teacher!=null){
            return teacher;
        }else{
            throw new RException(REnum.LOGIN_ERR);
        }
    }

    public Teacher insert(Teacher teacher){
        return teacherRepository.save(teacher);

    }

    public Teacher update(Teacher teacher){
        return teacherRepository.save(teacher);
    }

    public void delete(Teacher teacher){
        teacherRepository.delete(teacher);
    }
    public void delete(Integer id){
        Teacher byId = teacherRepository.getById(id);
        String name = byId.getName();

        Teacher teacher=new Teacher();
        teacher.setId(id);

        teacherRepository.delete(teacher);
    }

    public Teacher getById(Integer id){

        Teacher teacher=teacherRepository.findById(id).orElse(null);
        return teacher;
    }
}
